/*
 * @Descripttion: 
 * @version: 
 * @Author: by
 * @Date: 2021-05-20 10:05:52
 * @LastEditors: tc
 * @LastEditTime: 2022-02-28 14:31:06
 */
import router from '../router/index'
import axios from 'axios'
import { ElMessage } from 'element-plus'
let token = localStorage.getItem('token')

const service = axios.create({
    timeout: 15000,
    headers: {
        Authorization: token
    }
})

service.interceptors.request.use(
    config => {
        let apiUrl = config.url
        let whiteList = [
            '/scareen/equitmentRun/findByAllStations','/scareen/equitmentRun/findByEquit','/scareen/equitmentRun/findByRisk','/web/auth/login','/web/auth/codeLogin','/web/auth/changePwd','/phone/sendCode','/web/auth/randomCode',
            '/web/auth/forgetPwd'
        ] // 不需要请求头携带token的接口
        let needAuthorization = whiteList.includes(apiUrl)
        let accesstoken = localStorage.getItem('token')
        config.headers.Authorization = accesstoken
        // console.log('该接口是否需要登录：true为不需要',needAuthorization,'请求接口：',apiUrl)
        if(needAuthorization) {
            return config
        } else {
            if(!accesstoken) {
                router.push('/login')
                return
            }else {
                return config
            }
        }
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        if(response.data.code === 403) {
            router.push('/403')
        }  else if (response.status === 200) {
            if(response.data.code == 200) {
                if(!response.data.data){
                    response.data.data='';
                }
                return Promise.resolve(response.data)
            }else if(response.data.code == 403) {
                router.push('/403')
            } else if(response.data.code == 401) {
                router.push('/login')
            } else if(response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
                return Promise.resolve(response.data)                                                                            
            } else {
                return Promise.reject(response.data)
            }
        } else {
            Promise.reject(response.data)
        }
    },
    error => {
        if(error.response.data.code == 401) {
            // ElMessage.error(error.response.data.message)
            router.push('/login')
        } else if(error.response.data.code == 403) {
            router.push('/403')
        }
        return Promise.reject(error.response)
    }
)

export default service
